package com.merak.rebot.python;

import com.alibaba.fastjson.JSON;
import com.merak.rebot.common.FileDirInfo;
import com.merak.rebot.common.PythonStatus;
import com.merak.rebot.config.MRebotsConfig;
import com.merak.rebot.utils.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class MerakPythonExecutor {

    @Autowired
    private MRebotsConfig mrebotsConfig;

//    //超时时间/秒
//    @Value("${meraktech.timeout.time}")
//    private long timeoutTime;
//
//    public void doExecutor(String path, String pythonName, String param){
//        String pythonParamName = path+File.separator+pythonName+"param";
//        log.debug("开始生成参数文件，{}",pythonParamName);
//        long l1 = System.currentTimeMillis();
//        generateParamFile(pythonParamName,param);
//        long l2 = System.currentTimeMillis();
//        log.debug("生成参数文件完成，{}，用时{}",pythonParamName,l2-l1);
//        log.debug("开始执行脚本，脚本文件{}",path+pythonName);
//        CommandResult result = CommandUtils.exec(path + File.separator + pythonName,timeoutTime);
//        if (result != null)
//        {
//            if (result.getError()!=null) {
//                log.error("Error:" + result.getError());
//            }
//        }
//        long l3 = System.currentTimeMillis();
//        log.debug("执行脚本完成，脚本文件{}，用时{}",path+pythonName,l3-l2);
//        log.debug("开始移动脚本文件到新目录");
//        moveParamFile(path,pythonName,path+File.separator+"history",FileUtil.getBakFileName(pythonName));
//        long l4 = System.currentTimeMillis();
//        log.debug("移动脚本文件到新目录完成，用时{}",l4-l3);
//        log.debug("开始移动脚本参数文件到新目录");
//        moveParamFile(path,pythonName+"param",path+File.separator+"history",FileUtil.getBakFileName(pythonName+".param"));
//        long l5 = System.currentTimeMillis();
//        log.debug("移动脚本参数文件到新目录完成，用时{}",l5-l4);
//    }
//
//    public static void main(String[] args) {
//        PythonStatus pythonStatus = new PythonStatus();
//        pythonStatus.setStartTime(CtDateUtils.dateToString(new Date()));
//        pythonStatus.setEndTime(CtDateUtils.dateToString(new Date()));
//        pythonStatus.setStatus("done");
//        pythonStatus.setRemark("执行成功");
//        System.out.println(JSON.toJSONString(pythonStatus));
//
//    }

    public void generateParamFile(String paramName, String param) {
        try {
            FileUtils.writeStringToFile(new File(paramName),param, StandardCharsets.UTF_8);
        } catch (IOException e) {
            log.error("生成param文件失败，文件名{}",paramName);
            e.printStackTrace();
        }

    }

//    public void selectStatusData(List<PythonStatus> pythonLogs, String logPath) throws IOException {
//        if(new File(logPath).exists()) {
//            String[] extensions = new String[]{"status"};
//            //按时例序，只取前15条记录
//            Collection<File> logs = FileUtils.listFiles(new File(logPath), extensions, false);
//            logs = logs.stream().sorted(Comparator.comparing(File::lastModified)).limit(mrebotsConfig.getRebots().getSelectMaxSize()).collect(Collectors.toList());
//            for (File item : logs) {
//                String statusBody = FileUtils.readFileToString(item, StandardCharsets.UTF_8);
//                PythonStatus oneLog = JSON.parseObject(statusBody, PythonStatus.class);
//                if(null == oneLog) {
//                    continue;
//                }
//                pythonLogs.add(oneLog);
//            }
//        }
//    }

    public void selectLogsData(List<PythonStatus> pythonLogs, String logPath, String name) throws IOException {
        if(new File(logPath).exists()) {
            String[] extensions = new String[]{"status"};
            //按时例序，只取前15条记录
            Collection<File> logs = FileUtils.listFiles(new File(logPath), extensions, false);
            logs = logs.stream().sorted(Comparator.comparing(File::lastModified)).limit(mrebotsConfig.getRebots().getSelectMaxSize()).collect(Collectors.toList());
            for (File item : logs) {
                String statusBody = FileUtils.readFileToString(item, StandardCharsets.UTF_8);
                PythonStatus oneLog = JSON.parseObject(statusBody, PythonStatus.class);
                if(null != oneLog && StringUtils.isNotEmpty(oneLog.getName()) && (StringUtils.isEmpty(name) || oneLog.getName().contains(name))) {
                    pythonLogs.add(oneLog);
                }

            }
        }
    }

    public void moveParamFile(String oldPath, String oldFileName, String newPath, String newFileName) {
        try {
            //生成新路径
            FileUtil.isDirectory(newPath);
            FileUtil.moveFileNewDelSR(oldPath,newPath,oldFileName,newFileName);
        } catch (Exception e) {
            log.error("移动文件失败，文件名{}",oldFileName);
            e.printStackTrace();
        }

    }

    public List<File> getFileDirs(String queryName, String path) {
        File pathFile = new File(path);
        File[] searchFiles = pathFile.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                if(!file.isDirectory()) {
                    return false;
                }
                String name = file.getName();
                //若指定查询字符串不为空,则要进行模糊查询
                if(!StringUtils.isEmpty(queryName) && !name.contains(queryName)) {
                    return false;
                }
                if("logs".equals(name)||"history".equals(name)){
                    return false;
                }
                return true;
            }
        });
        List<File> fileList = new ArrayList<>();
        if(searchFiles != null && searchFiles.length > 0) {
            Collection<File> dirs = Arrays.asList(searchFiles);
            //2.按时间倒序排序, 最多只最近20个
            fileList = dirs.stream().sorted(Comparator.comparing(File::lastModified)).collect(Collectors.toList());
        }
        return fileList;
    }

    public List<File> getFileDirInfoList(String queryName, String path, List<File> dirs, int index, String key, List<FileDirInfo> fileDirInfoList, String value, String pKey) {
        FileDirInfo fileDirInfo = new FileDirInfo();
        fileDirInfo.setKey(key);
        fileDirInfo.setPKey(pKey);
        fileDirInfo.setTitle(dirs.get(index).getName());
        fileDirInfo.setValue(value);
        fileDirInfo.setChildren(new ArrayList<>());
        fileDirInfoList.add(fileDirInfo);
        return MerakPythonExecutor.this.getFileDirs(queryName, path + File.separator + value);
    }


}
